package edu.scau.divineplace.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import edu.scau.divineplace.entity.dos.FavoriteDO;
import edu.scau.divineplace.entity.dos.JournalDO;
import edu.scau.divineplace.entity.dos.MusicDiscListDO;
import edu.scau.divineplace.entity.dos.UserDO;
import edu.scau.divineplace.entity.enums.BaseEnum;
import edu.scau.divineplace.entity.enums.FavoriteTypeEnum;
import edu.scau.divineplace.entity.enums.IsDeletedEnum;
import edu.scau.divineplace.entity.vo.FavoriteUserVO;
import edu.scau.divineplace.entity.vo.JournalVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: x1aolone
 * @Date: 2020/12/11 15:48
 */
@Service
public class FavoriteService {

    @Autowired
    private ImportMapperService importMapperService;

    /**
     * 通过内容id获取收藏该内容的用户列表，支持分页
     * @param contentId
     * @param currentPage
     * @param pageSize
     * @return
     */
    public List<FavoriteUserVO> listFavoriteUser(Long contentId, Integer currentPage, Integer pageSize) {
        if (currentPage == null) {
            currentPage = -1;
        }
        if (pageSize == null) {
            pageSize = -1;
        }
        Page<FavoriteDO> favoritePage = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<FavoriteDO> query = Wrappers.<FavoriteDO>lambdaQuery()
                .eq(FavoriteDO::getContentId, contentId)
                .eq(FavoriteDO::getType, FavoriteTypeEnum.OTHER)
                .orderByDesc(FavoriteDO::getUpdateTime)
                .orderByDesc(FavoriteDO::getCreateTime);
        favoritePage = importMapperService.favoriteMapper.selectPage(favoritePage, query);

        List<FavoriteUserVO> VOS = Lists.newArrayList();
        for (FavoriteDO favoriteDO : favoritePage.getRecords()) {
            UserDO userDO = importMapperService.userMapper.selectById(favoriteDO.getUserId());
            FavoriteUserVO VO = FavoriteUserVO.builder()
                    .createTime(favoriteDO.getCreateTime())
                    .userInfo(userDO)
                    .build();
            VOS.add(VO);
        }
        return VOS;
    }

    /**
     * 通过用户id和内容id获取收藏信息
     * @param userId
     * @param contentId
     * @return
     */
    public FavoriteDO selectByUserIdAndContentId (Long userId, Long contentId) {
        LambdaQueryWrapper<FavoriteDO> query = Wrappers.<FavoriteDO>lambdaQuery()
                .eq(FavoriteDO::getContentId, contentId)
                .eq(FavoriteDO::getUserId, userId)
                .last("limit 1");
        return importMapperService.favoriteMapper.selectOne(query);
    }

    /**
     * 判断用户是否收藏内容
     * @param userId
     * @param contentId
     */
    public Boolean judge(Long userId, Long contentId){
        if (userId == null || contentId == null) {
            return null;
        }
        FavoriteDO DO = selectByUserIdAndContentId(userId, contentId);
        return DO != null;
    }


    public Integer countFavoriteNum(FavoriteTypeEnum type, Long contentId){
        LambdaQueryWrapper<FavoriteDO> query = Wrappers.<FavoriteDO>lambdaQuery()
                .eq(FavoriteDO::getContentId, contentId);
        if (type != null) {
            query.eq(FavoriteDO::getType, type);
        }
        Integer favoriteNum = importMapperService.favoriteMapper.selectCount(query);
        return favoriteNum;
    }

    /**
     * 用户收藏内容
     * @param userId
     * @param contentId
     * @param type 收藏类型，其他/想看/在看/未看
     */
    public void add(Long userId, Long contentId, Integer type){
        FavoriteTypeEnum favoriteTypeEnum = BaseEnum.typeOf(FavoriteTypeEnum.class, type);
        Preconditions.checkNotNull(favoriteTypeEnum, "收藏类型错误");
        FavoriteDO DO = selectByUserIdAndContentId(userId, contentId);
        if (DO == null) {
            // 没收藏，建立新的
            DO = new FavoriteDO();
            DO.setUserId(userId);
            DO.setContentId(contentId);
            DO.setType(favoriteTypeEnum);
            importMapperService.favoriteMapper.insert(DO);
        }
        else if (!favoriteTypeEnum.equals(DO.getType())) {
            // 已收藏，检查内容是否需要更新
            update(userId, contentId, favoriteTypeEnum);
        }
    }

    /**
     * 用户收藏内容
     * @param userId
     * @param contentId
     * @param type 收藏类型，其他/想看/在看/未看
     */
    public void update(Long userId, Long contentId, Integer type){
        FavoriteTypeEnum favoriteTypeEnum = BaseEnum.typeOf(FavoriteTypeEnum.class, type);
        Preconditions.checkNotNull(favoriteTypeEnum, "收藏类型错误");
        update(userId, contentId, favoriteTypeEnum);
    }

    /**
     * 更新收藏类型
     * @param userId
     * @param contentId
     * @param favoriteTypeEnum 收藏类型枚举，其他/想看/在看/未看
     */
    public void update(Long userId, Long contentId, FavoriteTypeEnum favoriteTypeEnum){
        LambdaUpdateWrapper<FavoriteDO> updateWrapper = Wrappers.<FavoriteDO>lambdaUpdate()
                .eq(FavoriteDO::getContentId, contentId)
                .eq(FavoriteDO::getUserId, userId)
                .set(FavoriteDO::getType, favoriteTypeEnum);
        // entity为null的时候不会自动填充，所以传个对象进去
        importMapperService.favoriteMapper.update(new FavoriteDO(), updateWrapper);
    }


    /**
     * 用户取消收藏
     * @param userId
     * @param contentId
     */
    public void delete(Long userId, Long contentId){
        Preconditions.checkNotNull(userId);
        Preconditions.checkNotNull(contentId);
        LambdaQueryWrapper<FavoriteDO> query = Wrappers.<FavoriteDO>lambdaQuery()
                .eq(FavoriteDO::getContentId, contentId)
                .eq(FavoriteDO::getUserId, userId);
        importMapperService.favoriteMapper.delete(query);
    }

    /**
     * 用户取消收藏
     * @param favoriteId
     */
    public void delete(Long favoriteId){
        Preconditions.checkNotNull(favoriteId);
        importMapperService.favoriteMapper.deleteById(favoriteId);
    }
}
